package com.qdy.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.qdy.entity.Order;
import com.qdy.pay.common.StreamUtil;
import com.qdy.pay.common.Util;
import com.qdy.pay.mode.PayCallbackData;
import com.qdy.pay.mode.WeiXinOrderResData;
import com.qdy.repository.OrderRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * <xml><appid><![CDATA[wxf669876309ce1505]]></appid>
 <bank_type><![CDATA[CFT]]></bank_type>
 <cash_fee><![CDATA[50]]></cash_fee>
 <fee_type><![CDATA[CNY]]></fee_type>
 <is_subscribe><![CDATA[N]]></is_subscribe>
 <mch_id><![CDATA[1453486202]]></mch_id>
 <nonce_str><![CDATA[1mlr5mqzl5athjgize5r63uvaka4sfne]]></nonce_str>
 <openid><![CDATA[oMXPs0Kj2KNK5efSnYcFlhulIfjw]]></openid>
 <out_trade_no><![CDATA[000001408798054]]></out_trade_no>
 <result_code><![CDATA[SUCCESS]]></result_code>
 <return_code><![CDATA[SUCCESS]]></return_code>
 <sign><![CDATA[2D8CA3296DC742326A1FCB5B4F5AAA21]]></sign>
 <time_end><![CDATA[20170503033856]]></time_end>
 <total_fee>50</total_fee>
 <trade_type><![CDATA[JSAPI]]></trade_type>
 <transaction_id><![CDATA[4003102001201705039319242824]]></transaction_id>
 </xml>

 * 微信回调接口
 * Created by qudingyi on 2017/4/30.
 */
@Controller
public class PayCallback {
    @Autowired
    private OrderRepository orderRepository;
    private Logger logger= LoggerFactory.getLogger(PayCallback.class);
    @RequestMapping("/payCallback")
    public void payCalback(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String reqParams = StreamUtil.read(request.getInputStream());
        logger.info("================支付结果:"+reqParams);
        PayCallbackData data= (PayCallbackData) Util.getObjectFromXML(reqParams,PayCallbackData.class);
        if("SUCCESS".equals(data.getReturn_code())){
            Order order=orderRepository.findByOrderNo(data.getOut_trade_no());
            order.setStatu(1);
            order.setTimeEnd(data.getTime_end());
            orderRepository.save(order);
        }
        StringBuffer sb = new StringBuffer("<xml><return_code>SUCCESS</return_code><return_msg>OK</return_msg></xml>");
        response.getWriter().append(sb.toString());
    }
}
